package com.tensquare.article.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Date 2021/3/21 15:01
 */
@Service
@Transactional
public class ArticleService {

    @Autowired
    private ArticleDao articleDao;

    @Autowired
    private RedisTemplate redisTemplate;

    public void examine(String articleId) {
        articleDao.update(new UpdateWrapper<Article>().eq("id", articleId).set("state", 1));
    }

    public void thumbup(String articleId) {
        articleDao.update(new UpdateWrapper<Article>().eq("id", articleId).setSql("thumbup = thumbup + 1"));
    }

    public Article findById(String articleId) {
        Article article = (Article) redisTemplate.opsForValue().get("article:" + articleId);
        if(null == article){
            article= articleDao.getById(articleId);
            redisTemplate.opsForValue().set("article:"+articleId,article);
            redisTemplate.expire("article:"+articleId,10, TimeUnit.SECONDS);
        }
        return article;
    }

    public void deleteById(String articleId) {
        articleDao.removeById(articleId);
        redisTemplate.delete("article:"+articleId);
    }
}
